package com.byzk.p2p.admin.fuiou.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.byzk.p2p.admin.bank.dto.BankCard;
import com.byzk.p2p.admin.bank.service.BankCardService;
import com.byzk.p2p.admin.base.controller.BaseController;
import com.byzk.p2p.admin.base.util.BaseUtil;
import com.byzk.p2p.admin.base.util.DateUtils;
import com.byzk.p2p.admin.base.util.JsonMsg;
import com.byzk.p2p.admin.borrow.dto.Borrow;
import com.byzk.p2p.admin.borrow.dto.UserTender;
import com.byzk.p2p.admin.borrow.service.BorrowService;
import com.byzk.p2p.admin.borrow.service.TenderService;
import com.byzk.p2p.admin.borrow.vo.BorrowVo;
import com.byzk.p2p.admin.fuiou.config.Config;
import com.byzk.p2p.admin.fuiou.dto.PreAuth;
import com.byzk.p2p.admin.fuiou.dto.RegisterDto;
import com.byzk.p2p.admin.fuiou.dto.TransferToFreezenDto;
import com.byzk.p2p.admin.fuiou.service.PreAuthCancelService;
import com.byzk.p2p.admin.fuiou.dto.QueryBalanceDto;
import com.byzk.p2p.admin.fuiou.util.SecurityUtils;
import com.byzk.p2p.admin.fuiou.util.WebUtils;
import com.byzk.p2p.admin.fuiou.util.XmlUtils;
import com.byzk.p2p.admin.money.dto.BorrowPayment;
import com.byzk.p2p.admin.money.dto.BorrowPaymentDetail;
import com.byzk.p2p.admin.money.service.BorrowPaymentDetailService;
import com.byzk.p2p.admin.money.service.BorrowPaymentService;
import com.byzk.p2p.admin.money.service.FundRecordService;
import com.byzk.p2p.admin.money.util.FundRecordType;
import com.byzk.p2p.admin.money.vo.BorrowPaymentVo;
import com.byzk.p2p.admin.system.dto.Callback;
import com.byzk.p2p.admin.system.dto.SystemConfig;
import com.byzk.p2p.admin.system.service.CallbackService;
import com.byzk.p2p.admin.system.service.SystemService;
import com.byzk.p2p.admin.user.dao.UserDao;
import com.byzk.p2p.admin.user.dto.InviteRef;
import com.byzk.p2p.admin.user.dto.User;
import com.byzk.p2p.admin.user.dto.UserAccount;
import com.byzk.p2p.admin.user.dto.UserAuth;
import com.byzk.p2p.admin.user.service.UserAccountService;
import com.byzk.p2p.admin.user.service.UserAuthService;
import com.byzk.p2p.admin.user.service.UserService;
import com.byzk.p2p.front.service.FrontUserService;

/**
 * 富友账户controller
 * @author suker
 *
 */
@Controller
@Scope("prototype")
@RequestMapping("/fuion")
public class FuionAccountController extends BaseController {

	@Autowired
	private UserService userService;
	@Autowired
	private FrontUserService frontUserService;
	@Autowired
	private UserAuthService authService;
	@Autowired
	private BankCardService bankService;
	@Autowired
	private CallbackService callbackService;
	@Autowired
	private BorrowService borrowService;
	@Autowired
	private TenderService tenderservice;
	@Autowired
	private BorrowPaymentService borrowPaymentService;
	@Autowired
	private BorrowPaymentDetailService borrowPaymentDetailService;
	@Autowired
	private UserAccountService accountService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private FundRecordService fundService;
	@Autowired
	private UserDao userDao;
	@Autowired
	private PreAuthCancelService preAuthCancelService ;
	private static Logger logger = Logger.getLogger(FuionAccountController.class);
	/**
	 * 开户：开通第三方托管
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/register")
	public String register(@RequestParam("userId") Integer userId) throws Exception {
		try {
			User user=userService.getById(userId);
			UserAuth auth=authService.getAuthByUidAndType(userId, "id5");
			List<BankCard> cardList=bankService.listCardByUserId(userId);
			RegisterDto dto=new RegisterDto();
			
			dto.setBank_nm(cardList.get(0).getBankName());
			dto.setCapAcntNm("");
			dto.setCapAcntNo(cardList.get(0).getCardNo());
			dto.setCertif_id(auth.getAuthName());
			dto.setCity_id(cardList.get(0).getCityCode());
			dto.setCust_nm(user.getRealname());
			dto.setEmail("");
			dto.setPassword(user.getDealPassword());
			dto.setLpassword(user.getLoginPassword());
			dto.setMchnt_cd(Config.mchnt_cd);
			dto.setMchnt_txn_ssn(DateUtils.getFullFormat()+(new Random().nextInt(8999)+1000));
			dto.setMobile_no(user.getPhone());
			dto.setParent_bank_id(cardList.get(0).getBankName());
			dto.setRem("");
			String inputStr=dto.regSignVal();
			dto.setSignature(SecurityUtils.sign(inputStr));
			//http请求富友开户接口并获取返回数据
			String backStr;
		
			backStr = WebUtils.sendHttp(Config.reg_url,dto);

			System.out.println(backStr);
			
			Callback callback=new Callback("开户",backStr,new Date());
			callbackService.saveOrUpdate(callback);
			
			String resp_code=XmlUtils.getXmlNodeValue(backStr, "resp_code");
			String mchnt_cd=XmlUtils.getXmlNodeValue(backStr, "mchnt_cd");
			if("0000".equals(resp_code) && Config.mchnt_cd.equals(mchnt_cd)){
				/**
				 * 开户奖励
				 */
				SystemConfig config=systemService.listSystemConfig();
				UserAccount account=accountService.getByUserId(user.getId());
	
				/** 开户成功之后，同步平台账户和金账户金额数据**/
				Double balance=account.getBalance();
				if(balance>0){
					//同步平台账户和金账户金额数据
					String code = accountService.updateBalance(account.getUserId(), balance);
					if("0000".equals(code)){
						//开通托管账户奖励::上线得到邀请奖励,本人得到开通托管账户奖励
						setInviteMoney(user, config, account);						
					}					
				}else{
					//开通托管账户奖励::上线得到邀请奖励,本人得到开通托管账户奖励
					setInviteMoney(user, config, account);						
				}

			}
//			else if("5343".equals(resp_code) || "5851".equals(resp_code)) { //TODO 仅供测试使用-----用户已开户直接认定为注册成功
//				user.setFuionAccount("Y");
//				userService.saveOrUpdate(user);
//				/**
//				 * 开户奖励
//				 */
//				SystemConfig config=systemService.listSystemConfig();
//				UserAccount account=accountService.getByUserId(user.getId());
//				account.setStayAmount(account.getStayAmount()+config.getRegReward());
//				accountService.saveOrUpdate(account);
//				userService.saveOrUpdate(user);
//				
//				/** 为邀请人添加奖励 **/
//				InviteRef inviteRef = userService.getInviteRefByUserId(user.getId());
//				if(inviteRef != null){
//					int inviteCount = frontUserService.inviteCountToPid(inviteRef.getPid());
//					Double inviteMoney =  0.0;
//					if(inviteCount <= 20) {
//						inviteMoney = config.getInviteReward();
//					}else if(inviteCount > 20 && inviteCount <= 50) {
//						inviteMoney = 100.00;
//					}else if(inviteCount > 50) {
//						inviteMoney = 200.00;
//					}
//					UserAccount inviteAccount = accountService.getByUserId(inviteRef.getPid());
//					inviteAccount.setStayAmount(inviteAccount.getStayAmount()+inviteMoney);
//					accountService.saveOrUpdate(inviteAccount);
//					fundService.addFundRecord(inviteAccount.getUserId(), inviteMoney, 0.0, "PC", "邀请奖励", FundRecordType.Type.STAY_MONEY.index, 0.0);
//				}
//				
//				fundService.addFundRecord(user.getId(), config.getRegReward(), 0.0, "PC", "开通托管账户奖励", FundRecordType.Type.STAY_MONEY.index, 0.0);
//				session.setAttribute("_user", user);
//				super.printJSON(new JsonMsg(-1, "开户成功"));
//			}
			else{
				super.printJSON(new JsonMsg(1, "开户失败",resp_code));
			}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			super.printJSON(new JsonMsg(2, "开户失败","系统数据异常"));
			return null;
		}
		
	}

	/**
	 * 开通托管账户奖励::上线得到邀请奖励,本人得到开通托管账户奖励
	 * @param user
	 * @param config
	 * @param account
	 * @throws Exception
	 */
	private void setInviteMoney(User user, SystemConfig config, UserAccount account) throws Exception {
		user.setFuionAccount("Y");
		userService.saveOrUpdate(user);

		account.setStayAmount(account.getStayAmount()+config.getRegReward());
		accountService.saveOrUpdate(account);
		
		/** 为邀请人添加奖励 **/
		InviteRef inviteRef = userService.getInviteRefByUserId(user.getId());
		if(inviteRef != null){
			int inviteCount = frontUserService.inviteCountToPid(inviteRef.getPid());
			Double inviteMoney =  0.0;
			if(inviteCount < 20) {
				inviteMoney = config.getInviteReward();
			}else if(inviteCount >= 20 && inviteCount < 50) {
				inviteMoney = 100.00;
			}else if(inviteCount >= 50) {
				inviteMoney = 200.00;
			}
			UserAccount inviteAccount = accountService.getByUserId(inviteRef.getPid());
			inviteAccount.setStayAmount(inviteAccount.getStayAmount()+inviteMoney);
			accountService.saveOrUpdate(inviteAccount);
			//上线得到邀请奖励
			fundService.addFundRecord(inviteAccount.getUserId(), inviteMoney, 0.0, "PC", "邀请奖励", FundRecordType.Type.STAY_MONEY.index, 0.0);
		}
		//本人得到开通托管账户奖励
		fundService.addFundRecord(user.getId(), config.getRegReward(), 0.0, "PC", "开通托管账户奖励", FundRecordType.Type.STAY_MONEY.index, 0.0);
		session.setAttribute("_user", user);
		super.printJSON(new JsonMsg(-1, "开户成功"));
	}
	
	/**
	 * 预授权(投资)
	 * @return
	 */
	@RequestMapping(value="/transfer/freezen")
	public String transferToFreezen(@RequestParam("borrowId") int borrowId,
									@RequestParam("userId") int userId,
									@RequestParam("amount") String amount){
		synchronized (FuionAccountController.class) {
			BorrowVo vo=borrowService.detailBorrowVo(borrowId);
			User tenderUser=userService.getById(userId);
			User borrowUser=userService.getById(vo.getBorrowUserId());
			
			PreAuth auth=new PreAuth();
			auth.setMchnt_cd(Config.mchnt_cd);
			auth.setMchnt_txn_ssn(DateUtils.getFullFormat()+(new Random().nextInt(8999)+1000));
			auth.setOut_cust_no(tenderUser.getPhone());
			auth.setIn_cust_no(borrowUser.getPhone());
			auth.setAmt((int)Double.parseDouble(amount)*100+"");
			auth.setRem("");
			String inputStr=auth.regSignVal();
			auth.setSignature(SecurityUtils.sign(inputStr));
			
			System.out.println("----明文参数："+inputStr);
			
			String backStr="";
			try {
				backStr = WebUtils.sendHttp(Config.pre_auth_url,auth);
				
				System.out.println("-------回调结果:"+backStr);
				
				Callback callback=new Callback("预授权",backStr,new Date());
				callbackService.saveOrUpdate(callback);
				
				String resp_code=XmlUtils.getXmlNodeValue(backStr, "resp_code");
				String mchnt_cd=XmlUtils.getXmlNodeValue(backStr, "mchnt_cd");
				String mchnt_txn_ssn=XmlUtils.getXmlNodeValue(backStr, "mchnt_txn_ssn");
				String contract_no=XmlUtils.getXmlNodeValue(backStr, "contract_no");
				if("0000".equals(resp_code) && Config.mchnt_cd.equals(mchnt_cd)){
					
					int result=tenderservice.addTender(borrowId,userId,Double.parseDouble(amount),mchnt_txn_ssn,contract_no);
					if(result==1){
						super.printJSON(new JsonMsg(-1, "划拨成功"));
					}else{					
						super.printJSON(new JsonMsg(1, "划拨失败","标已投满！"));
					}
				}else{
					super.printJSON(new JsonMsg(1, "划拨失败",resp_code));
				}
			}catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}
	}
	
//	/**
//	 * 划拨预冻结(满标)
//	 * @return
//	 * @throws Exception 
//	 */
//	@RequestMapping("/borrow/complete")
//	public String complete(@RequestParam("borrowId") int borrowId) throws Exception{
//		Borrow borrow=borrowService.getBorrowById(borrowId);
//		if("check".equals(borrow.getStatus())){
//			List<UserTender> tenderList=tenderservice.listTender(borrowId);
//			BorrowVo vo=borrowService.detailBorrowVo(borrowId);
//			User borrowUser=userService.getById(vo.getBorrowUserId());
//			int num=0;
//			for (UserTender userTender : tenderList) {
//				User tenderUser=userService.getById(userTender.getUserId());
//				TransferToFreezenDto dto=new TransferToFreezenDto();
//				dto.setMchnt_cd(Config.mchnt_cd);
//				dto.setMchnt_txn_ssn(DateUtils.getFullFormat()+(new Random().nextInt(8999)+1000));
//				dto.setOut_cust_no(tenderUser.getPhone());
//				dto.setIn_cust_no(borrowUser.getPhone());
//				dto.setContract_no(userTender.getContractNo());
//				dto.setRem("");
//				dto.setAmt((int)(userTender.getAmount()*100)+"");
//				String inputStr=dto.regSignVal();
//				dto.setSignature(SecurityUtils.sign(inputStr));
//				
//				String backStr = WebUtils.sendHttp(Config.transfer_to_freezen_url,dto);
//
//				System.out.println(backStr);
//				
//				Callback callback=new Callback("划拨预冻结",backStr,new Date());
//				callbackService.saveOrUpdate(callback);
//				
//				String resp_code=XmlUtils.getXmlNodeValue(backStr, "resp_code");
//				String mchnt_cd=XmlUtils.getXmlNodeValue(backStr, "mchnt_cd");
//				if("0000".equals(resp_code) && Config.mchnt_cd.equals(mchnt_cd)){
//					num++;
//				}
//			}
//			
//			if(num==tenderList.size()){
//				tenderservice.compeleteBorrow(borrow);
//				super.printJSON(new JsonMsg(-1, "操作成功"));
//			}else{
//				super.printJSON(new JsonMsg(1, "操作失败"));
//			}
//		}
//		return null;
//	}
	
	/**
	 * 划拨预冻结(满标复审)
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/borrow/complete")
	public String complete(@RequestParam("borrowId") int borrowId) throws Exception{
		Borrow borrow=borrowService.getBorrowById(borrowId);
		if("check".equals(borrow.getStatus())){
			List<UserTender> tenderList=tenderservice.listTender(borrowId);
			BorrowVo vo=borrowService.detailBorrowVo(borrowId);
			User borrowUser=userService.getById(vo.getBorrowUserId());
			int num=0;
			List<Callback> listCallback = new ArrayList<Callback>();
			for (UserTender userTender : tenderList) {
				User tenderUser=userService.getById(userTender.getUserId());
				TransferToFreezenDto dto=new TransferToFreezenDto();
				dto.setMchnt_cd(Config.mchnt_cd);
				dto.setMchnt_txn_ssn(DateUtils.getFullFormat()+(new Random().nextInt(8999)+1000));
				dto.setOut_cust_no(tenderUser.getPhone());
				dto.setIn_cust_no(borrowUser.getPhone());
				dto.setContract_no(userTender.getContractNo());
				dto.setRem("");
				double amt = BaseUtil.StringToDoubletoFixed2(userTender.getAmount()*100);
				dto.setAmt((int)(amt)+"");
				String inputStr=dto.regSignVal();
				dto.setSignature(SecurityUtils.sign(inputStr));
				
				String backStr = WebUtils.sendHttp(Config.transfer_to_freezen_url,dto);
				System.out.println(backStr);
				
				String resp_code=XmlUtils.getXmlNodeValue(backStr, "resp_code");
				String mchnt_cd=XmlUtils.getXmlNodeValue(backStr, "mchnt_cd");
				if("0000".equals(resp_code) && Config.mchnt_cd.equals(mchnt_cd)){
					num++;
				}
				
				Callback callback=new Callback("划拨预冻结",backStr,new Date());
				listCallback.add(callback);
			}
			callbackService.batchInsert(listCallback);
			if(num==tenderList.size()){
				//满标复审，更新迅泊达平台数据
				tenderservice.compeleteBorrow(borrow);
				super.printJSON(new JsonMsg(-1, "操作成功"));
			}else{
				super.printJSON(new JsonMsg(1, "操作失败"));
			}
		}
		return null;
	}
	
	/**
	 * 还款
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/repay")
	public String payment(@RequestParam("paymentId") int paymentId) throws Exception{
		String resp_code="";
		User user = (User)session.getAttribute("_user");
		user = userService.getById(user == null ?0:user.getId());
		try {
			if (user == null) {
				printJSON(new JsonMsg(1, "请先登录！"));
				return null;
			}
			BorrowPaymentVo borrowPaymentVo = borrowPaymentService.detail(paymentId);
			if (borrowPaymentVo == null ) {
				printJSON(new JsonMsg(1, "还款失败！未获取到该标的借款者信息！"));
				return null;
			}
			//查询金账户用户可用余额
			UserAccount account = getFuionAccountBalance(user);
			if (account == null || account.getBalance() == null || account.getBalance() <= 0d ) {
				printJSON(new JsonMsg(1, "还款失败！未获取到您的金账户信息！"));
				return null;
			}
			
			if (account.getBalance() < borrowPaymentVo.getNotPaymentTotal()) {
				printJSON(new JsonMsg(1, "还款失败！您的金账户可用余额不足,余额为</br>￥"+account.getBalance()+"元, 应还￥"+borrowPaymentVo.getNotPaymentTotal()+"元,请先充值！"));
				return null;
			}
			
			//查询平台用户可用余额
			UserAccount userAccount = accountService.getByUserId(user.getId());
			if (userAccount == null || userAccount.getBalance() == null || userAccount.getBalance() <= 0d ) {
				printJSON(new JsonMsg(1, "还款失败！未获取到您的平台账户信息，或者平台账户余额小于等于0！"));
				return null;
			}
			
			if (userAccount.getBalance() < borrowPaymentVo.getNotPaymentTotal()) {
				printJSON(new JsonMsg(1, "还款失败！您的迅泊达可用余额不足,应还</br>￥"+borrowPaymentVo.getNotPaymentTotal()+"元,请先充值！"));
				return null;
			}
			
			if (checkPayment(borrowPaymentVo.getBorrowId(), user.getId(), borrowPaymentVo.getPeriodIndex())) {
				int num = 0;
//				BorrowPayment payment = borrowPaymentService.getById(paymentId);
				if (!userService.checkIsFuionAccount(paymentId)) {
					printJSON(new JsonMsg(1, "还款失败！投资用户中有尚未开通第三方账户的用户！"));
					return null;
				}
//				User borrowUser = userService.getById(borrowPaymentVo.getUserId());
				List<BorrowPaymentDetail> detailList = borrowPaymentDetailService.selectDetailByPaymentId(paymentId);
				List<BorrowPaymentDetail> SuccPaymentList = new ArrayList<BorrowPaymentDetail>();
				List<Callback> listCallback = new ArrayList<Callback>();
				for (BorrowPaymentDetail detail : detailList) {
//					User tenderUser = userService.getById(detail.getUserId());
					TransferToFreezenDto dto = new TransferToFreezenDto();
					dto.setMchnt_cd(Config.mchnt_cd);
					dto.setMchnt_txn_ssn(DateUtils.getFullFormat() + (new Random().nextInt(8999) + 1000));
					dto.setOut_cust_no(user.getPhone());//借款用户电话
					dto.setIn_cust_no(detail.getTenderPhone());//投资用户电话
					if(detail.getIsChange() !=null && "Y".equals(detail.getIsChange())){
						User cUser = userDao.getUserByTenderUid(detail);//债权转让承接者信息
						if(cUser!=null &&cUser.getPhone()!=null && StringUtils.isNotBlank(cUser.getPhone()) ){
							dto.setIn_cust_no(cUser.getPhone());
						}
					}
					dto.setContract_no("");
					dto.setRem("还款");
					double amt = BaseUtil.StringToDoubletoFixed2(detail.getNotPaymentTotal()*100);
					dto.setAmt((int) (amt) + "");
					String inputStr = dto.regSignVal();
					dto.setSignature(SecurityUtils.sign(inputStr));

					String backStr;
					try {
						backStr = WebUtils.sendHttp(Config.transfer_to_freezen_url, dto);
						System.out.println(backStr);

						Callback callback = new Callback("划拨预冻结", backStr, new Date());
						listCallback.add(callback);
						
						resp_code = XmlUtils.getXmlNodeValue(backStr, "resp_code");
						String mchnt_cd = XmlUtils.getXmlNodeValue(backStr, "mchnt_cd");
						if ("0000".equals(resp_code) && Config.mchnt_cd.equals(mchnt_cd)) {
							num++;
							SuccPaymentList.add(detail);
						} else {
							break;
						}
					} catch (Exception e) {
						e.printStackTrace();
						printJSON(new JsonMsg(0, "系统异常,请稍后再试！"+e.getMessage()));
					}
				}
				callbackService.batchInsert(listCallback);
			
				if (num == detailList.size()) {
					borrowPaymentService.payment(paymentId);
					super.printJSON(new JsonMsg(-1, "还款成功"));
				}else {
					failPaymentRollBack(SuccPaymentList, user); //回滚记录
					super.printJSON(new JsonMsg(1, "还款失败", resp_code));
				}
			} else {
				printJSON(new JsonMsg(2, "请按照期数依次还款！"));
			}

		} catch (Exception e) {
			e.printStackTrace();
			printJSON(new JsonMsg(0, "系统异常,请稍后再试！"+e.getMessage()));
		}
		return null;
	}
	
	/**
	 * 根据paymentId和还款期数检查该期数之前的还款状态
	 * @param paymentId 
	 * @param index 还款当期
	 * @return
	 */
	public boolean checkPayment(Integer borrowId,Integer userId,Integer index){
		if(index==1){
			return true;
		}else{
			if(index>1){
				BorrowPaymentVo borrowPaymentVo = new BorrowPaymentVo();
				borrowPaymentVo.setUserId(userId);
				borrowPaymentVo.setBorrowId(borrowId);
				index=index-1;
				borrowPaymentVo.setPeriodIndex(index);
				List<BorrowPaymentVo> paymentList = borrowPaymentService.borrowUserRepayList(borrowPaymentVo);
				
				if("Y".equals(paymentList.get(0).getStatus())){
					return true;
				}else{
					return false;
				}
			}	
		}
		return false;
	}
	
	
//	/**
//	 * 
//	* <p>Description: 检查是否所有投资用户都开通第三方账户</p>
//	* <p>Company:xbd </p>
//	* @author:lilei
//	* @date:2016年9月23日上午11:14:36
//	 */
//	public  boolean checkIsFuionAccount(List<BorrowPaymentDetail> detail_list){
//	  int num=0;
//	  boolean isFuionAccount = false;
//	  for(BorrowPaymentDetail detail : detail_list){
//		  User user =  userService.getById(detail.getUserId());
//		  if("N".equals(user.getFuionAccount().trim())||"".equals(user.getFuionAccount().trim())) {
//			  break;
//		  }	else  if("Y".equals(user.getFuionAccount().trim())) {
//			  num++;
//		  }
//	  }
//	  if(num == detail_list.size()){
//		  isFuionAccount =  true;
//      }
//	  return isFuionAccount;
//  }
  
	/**
	 * 
	* <p>Description: 金账户还款金额回滚</p>
	* <p>Company:xbd </p>
	* @author:lilei
	* @date:2016年10月13日下午2:37:26
	 */
	public  void  failPaymentRollBack(List<BorrowPaymentDetail> detailList ,User borrowUser){
		if(detailList ==null || borrowUser== null ) {return;}
		for (BorrowPaymentDetail detail : detailList) {
			User tenderUser = userService.getById(detail.getUserId());
			TransferToFreezenDto dto = new TransferToFreezenDto();
			dto.setMchnt_cd(Config.mchnt_cd);
			dto.setMchnt_txn_ssn(DateUtils.getFullFormat() + (new Random().nextInt(8999) + 1000));
			dto.setOut_cust_no(tenderUser.getPhone());
			dto.setIn_cust_no(borrowUser.getPhone());
			dto.setContract_no("");
			dto.setRem("还款失败回滚");
			double amt = BaseUtil.StringToDoubletoFixed2(detail.getNotPaymentTotal() * 100);
			dto.setAmt((int) (amt) + "");
			String inputStr = dto.regSignVal();
			dto.setSignature(SecurityUtils.sign(inputStr));
			String backStr;
			try {
				backStr = WebUtils.sendHttp(Config.transfer_to_freezen_url, dto);
				System.out.println(backStr);

				Callback callback = new Callback("--------还款记录项回滚------", backStr, new Date());
				callbackService.saveOrUpdate(callback);
				String resp_code = XmlUtils.getXmlNodeValue(backStr, "resp_code");
				String mchnt_cd = XmlUtils.getXmlNodeValue(backStr, "mchnt_cd");
				if ("0000".equals(resp_code) && Config.mchnt_cd.equals(mchnt_cd)) {
					logger.info("------回滚记录成功------");
				} else {
					logger.info("-------回滚记录失败------");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 
	* <p>Description:查询客户的金账户可用余额 </p>
	* <p>Company:xbd </p>
	* @author:lilei
	* @date:2016年10月14日上午9:51:44
	 */
	public  UserAccount  getFuionAccountBalance(User borrowUser){
		UserAccount account = new UserAccount();
		try{
		    QueryBalanceDto	 dto = new QueryBalanceDto();
		 	dto.setMchnt_cd(Config.mchnt_cd);
			dto.setMchnt_txn_ssn(DateUtils.getFullFormat() + (new Random().nextInt(8999) + 1000));
			dto.setCust_no(borrowUser.getPhone());
			dto.setMchnt_txn_dt(DateUtils.FormatDate());
			String inputStr = dto.regSignVal();
			dto.setSignature(SecurityUtils.sign(inputStr));
			String backStr;
			backStr = WebUtils.sendHttp(Config.paltform_to_user_balance_url, dto);
			logger.info("接口调用信息"+backStr);
			Callback callback = new Callback("--------查询客户金账户可用余额------", backStr, new Date());
			callbackService.saveOrUpdate(callback);
			String resp_code = XmlUtils.getXmlNodeValue(backStr, "resp_code");
			String mchnt_cd = XmlUtils.getXmlNodeValue(backStr, "mchnt_cd");
			if ("0000".equals(resp_code) && Config.mchnt_cd.equals(mchnt_cd)) {
				logger.info("=====请求接口成功====="+backStr);
				account.setBalance(getXmlNodeDoubleValue(backStr,"ca_balance"));//可用余额
				account.setTotalAmount(getXmlNodeDoubleValue(backStr,"ct_balance"));//账户总余额
				account.setFreezen(getXmlNodeDoubleValue(backStr,"cf_balance"));//冻结金额
			} else {
				logger.info("-------请求接口失败------失败代码：【"+resp_code+"】");
				return account;
			}
		}catch(Exception e){
			logger.info("=====请求接口失败======"+e.getMessage());
		}
		return account;
	}

	private Double getXmlNodeDoubleValue(String backStr,String str) {
		String je = XmlUtils.getXmlNodeValue(backStr, str);
		je = null==je|| "".equals(je)?"0":je;
		return Double.parseDouble(je)/100;
	}
	
//	@RequestMapping("/test")
//	public void test(@RequestParam("borrowId") int borrowId,
//			@RequestParam("userId") int userId,
//			@RequestParam("code") String code){
//		preAuthCancelService.preAuthCancel(borrowId, userId, code);
//	}
}
